import concurrent.futures
import time

# 模拟发送请求的函数
def send_request(i):
    """
    模拟发送请求的函数，这里只是简单地模拟耗时操作
    :param i: 请求的编号
    :return: 请求的结果
    """
    print(f"Sending request {i}...")
    time.sleep(1)  # 模拟耗时操作
    print(f"Request {i} completed.")
    return f"Result of request {i}"

# 并发测试函数
def run_concurrent_test(concurrency):
    """
    执行并发测试
    :param concurrency: 并发数量
    :return: 测试结果列表
    """
    results = []  # 用于存储每个请求的结果

    # 使用 ThreadPoolExecutor 管理线程池
    with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as executor:
        # 提交并发任务
        futures = [executor.submit(send_request, i) for i in range(concurrency)]

        # 遍历已完成的 Future 对象，获取结果
        for future in concurrent.futures.as_completed(futures):
            try:
                result = future.result()  # 获取 Future 的结果
                if result:
                    results.append(result)  # 将结果添加到列表中
            except Exception as e:
                print(f"An error occurred: {e}")

    return results

# 主程序
if __name__ == "__main__":
    CONCURRENCY = 5  # 设置并发数量
    print(f"Starting concurrent test with {CONCURRENCY} threads...")

    # 执行并发测试
    start_time = time.time()
    test_results = run_concurrent_test(CONCURRENCY)

    # 打印测试结果
    print("\nTest results:")
    for result in test_results:
        print(result)

    # 计算并打印耗时
    end_time = time.time()
    print(f"\nTotal time taken: {end_time - start_time:.2f} seconds")

